package com.project.basis.utils;

import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.project.basis.R;
import com.project.basis.config.ProjectApplication;

/**
 * Created by ECLAIR on 2018/3/22.
 */
public class ToastUnits {

    private static Toast toast;

    private ToastUnits() {
    }

    private static void getToast() {
        if (toast == null) {
            toast = Toast.makeText(ProjectApplication.context, "", Toast.LENGTH_SHORT);
            LinearLayout linearLayout = (LinearLayout) toast.getView();
            linearLayout.setBackgroundColor(ProjectApplication.context.getResources().getColor(android.R.color.transparent));
            TextView messageTextView = (TextView) linearLayout.getChildAt(0);
            messageTextView.setTextSize(18);
            messageTextView.setTextColor(ProjectApplication.context.getResources().getColor(R.color.color_BBC8EB));
            messageTextView.setPadding(ToolsUtils.dptopx(12), ToolsUtils.dptopx(12),
                    ToolsUtils.dptopx(12), ToolsUtils.dptopx(12));
            messageTextView.setBackground(ProjectApplication.context.getResources().getDrawable(R.drawable.bg_toast));
            messageTextView.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
            messageTextView.getLayoutParams().height = LinearLayout.LayoutParams.WRAP_CONTENT;
        }
    }

    public static void showShortToast(CharSequence msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    public static void showShortToast(int resId) {
        showToast(resId, Toast.LENGTH_SHORT);
    }

    public static void showLongToast(CharSequence msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    public static void showLongToast(int resId) {
        showToast(resId, Toast.LENGTH_LONG);
    }

    private static void showToast(CharSequence msg, int duration) {
        try {
            getToast();
            toast.setText(msg);
            toast.setDuration(duration);
            toast.show();
        } catch (Exception ignored) {
        }
    }

    private static void showToast(int resId, int duration) {
        try {
            if (resId == 0) {
                return;
            }
            getToast();
            toast.setText(resId);
            toast.setDuration(duration);
            toast.show();
        } catch (Exception ignored) {
        }
    }

    public static void cancelToast() {
        if (toast != null) {
            toast.cancel();
        }
    }
}
